from pymongo import Connection
from time import time
import random
import csv
import subprocess
from XW_Inverter import XW_Inverter

PORT = '/dev/tty.usbserial-FTUTUPP2' #Enter the number needed here. 
ADDRESS = [0x89,0x65,0xc3]

Inverter = XW_Inverter(PORT,ADDRESS[0])

connection = Connection()
db = connection.string0001

# Takes the log file
subprocess.call(['/Users/batterylab/seeya_node/ftpDraw'],shell=True)
blah = open('mb-250.log')
blah = blah.read()
blah = blah.split(',')
print blah

#remove this from all UTC times to shift to Eastern Time
timeZone=4*60*60

# Database collection formation 
realtime = db.realtime
sensors = db.sensors
control = db.control.find_one({"label":0})
settings = db.settings
Nisensors = db.NIsensors.find_one({"label" : 0})

#read data from the inverter
Asoc= 0.0
Aiac= 0.0
Avac= 0.0
Aidc= 0.0
tpiac = 0.0
tpoac = 0.0

writer=({"label":0})

#mock inverter data

for i in range(0,3):
	ii=str(i);
	## Reading functions
	Inverter.address = ADDRESS[i]
	
	iac = Inverter.getACOutCurr()
	piac = Inverter.getACInPowe1()
	poac = Inverter.getACOutPower()
	idc = Inverter.getDCInCurr()
	vac = Inverter.getACInVolt1()
	vdc = Inverter.getDCOutVolt() 
	soc = Inverter.getBatSOC()
	charge = Inverter.getChargeState()
	invert = Inverter.getInvertState()
	temperture = Inverter.getBatTemp()
	tpoac = poac + tpoac
	tpiac = piac + tpiac
	Niv0 = Nisensors['Niv0']
	Niv1 = Nisensors['Niv1']
	Niv2 = Nisensors['Niv2']
	Niv3 = Nisensors['Niv3']
	
	#Write to the database
	writer.update( { "vdc" + ii : 50*random.random() ,
		"idc" + ii : idc ,
		"iac" + ii : iac ,
		"piac" + ii : piac,
		"poac" + ii : poac, 
		"vac" + ii : vac ,
		"vdc" + ii : vdc ,
		"address" + ii : ADDRESS[i],
		"soc" + ii : soc,
		"charge" + ii : charge,
		"invert" + ii : invert,
		"temperature"+ ii : temperture,
		"time" : 1000*(time()-timeZone),
		"tpiac"  : tpiac,
		"tpoac"  : tpoac,
		"Aiac"   : Aiac,
		"Aidc"   : Aidc,
		"Niv0"	 : Niv0/1000.0,
		"Niv1"	 : Niv1/1000.0,
		"Niv2"	 : Niv2/1000.0,
		"Niv3"	 : Niv3/1000.0
	} )
	Asoc=soc+ Asoc 
	Aiac=iac+ Aiac
	Avac=vac+ Avac
	Aidc=idc+ Aidc
	
	

sensors.update({'label':0},writer,True)


Asoc=0.33*soc
Avac=0.33*vac


#control current	
invert_threshold=control["invert_threshold"]
charge_threshold=control["charge_threshold"]
status=control["status"]
chargeState=control["charge_state"]
sellState=control["sell_state"]
maxChargeRate=control["max_charge_current"]
maxSellRate=control["max_sell_current"]/3
###################################################################
#Actual building laod
load = float(blah[6]) + float(blah[13]) #This converts the read values to floats for the load
load1 = float(blah[6]) 
load2 = float(blah[13])
meter = load
diff = 0
current = ((load-invert_threshold)/40)/20

print load
print maxSellRate
print sellState
print maxChargeRate
print chargeState

#print invert_threshold
#print charge_threshold
#print status

#don't have enough capacity to make a difference ...
capacityfactor=0.001

#need to account for soc
# set max current at 38 amps


## In auto mode, write these values based on above calculations
## If this is found, and I am still alive tomorrow - Wooo

if(sellState==1 or chargeState==1 or status==1):	
	writer=({"label":0})
	
	if(load>invert_threshold):
		invert=1
		charge=0
		if current < 38:
			current=(load-invert_threshold)/40
		else:
			current = 38
		diff=load-invert_threshold
		meter=invert_threshold
		
		## IF load is greater than the invert threshold, do this:
		for i in range(0,3):
			ii=str(i)
			writer.update( { "idc" + ii : current/3.0 ,
				"status" + ii : 1 , 
				"address" + ii : ADDRESS[i],
				"charge" + ii : 0,
				"sell" + ii : 1,
				"time" : 1000*(time()-timeZone),
				"sellrate" : maxSellRate*200,
				
				"chargerate" : maxChargeRate
				} )
			
			#Valerio had to change because pythos was giving errors
			if(sellState==1):
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setChargeState(0)
				Inverter.setSellMode(1)
				Inverter.setMaxSellAmp(current/20)
				
		settings.update({'label':0},writer,True)
		
	if(load<charge_threshold):
		invert=0
		charge=1
		if current < 38:
			current=(load-invert_threshold)/40
		else:
			current = 38
		diff=load-charge_threshold
		meter=charge_threshold
		
		## IF load is less than the charge threshold, do this:

		for i in range(0,3):
			ii=str(i)
			writer.update( { "idc" + ii : current/3.0 ,
				"status" + ii : 0 , 
				"address" + ii : ADDRESS[i],
				"charge" + ii : chargeState,
				"sell" + ii : 1,
				"time" : 1000*(time()-timeZone),
				"sellrate" : maxSellRate*200,
				"chargerate" : 90
				} )

			#Valerio added if statement -- py was failing
			if(chargeState==1):
				Inverter.address = ADDRESS[i]
				Inverter.setUserCommand()
				Inverter.setSellMode(0)
				Inverter.setChargeState(1)
				Inverter.setMaxChargeRate(90)	
			
		settings.update({'label':0},writer,True)
		
	

else:
	writer=({"label":0})

	for i in range(0,3):
		ii=str(i)
		writer.update( { "idc" + ii : current/3.0 ,
			"status" + ii : 0 , 
			"address" + ii : ADDRESS[i],
			"charge" + ii : chargeState,
			"sell" + ii : sellState,
			"time" : 1000*(time()-timeZone),
			"sellrate" : maxSellRate*200,
			"chargerate" : maxChargeRate
			} )
		
	settings.update({'label':0},writer,True)



#write realtime data	
# Add ACTUAL data
writer=({"load" : load,
		 "load1" : load1,
		 "load2" : load2,
		 "power":diff,
		 "meter":meter,
		 "soc": soc,
		"time":1000*(time()-timeZone),
		"Niv0" : Niv0/1000.0,
		"Niv1" : Niv1/1000.0,
		"Niv2" : Niv2/1000.0,
		"Niv3" : Niv3/1000.0,
		
	} ) 
realtime.insert(writer)


